﻿using System.Collections.Generic;

namespace Baggr
{
    using System;
    using System.Diagnostics;
    using System.Security.Cryptography;
    using System.Text;

    public static class StringHelper
    {
        /// <summary>
        /// Вычеслить гуид по строк.
        /// </summary>
        /// <param name="value">
        /// Обрабатываемая строка.
        /// </param>
        /// <returns>
        /// Гуид, который соответствует этой строке.
        /// </returns>
        public static Guid GetGuidByString(this string value)
        {
            if(string.IsNullOrEmpty(value))
                return new Guid();

            var data = Encoding.UTF8.GetBytes(value);
            var md5 = MD5.Create();
            Debug.Assert(md5 != null, "Алгоритм хеширования должен быть создан.");
            var hash = md5.ComputeHash(data);
            Debug.Assert(hash.Length == 16, "Хеш должен быть 16 байт.");
            return new Guid(hash);
        }

        public static Dictionary<string, int> GetWords(this string feedItemText)
        {
            if (string.IsNullOrEmpty(feedItemText))
                return new Dictionary<string, int>();

            var words = new Dictionary<string, int>(feedItemText.Length / 4);
            var firstLatter = 0;
            bool tagOpened = false;
            for (var currentLatter = 0; currentLatter <= feedItemText.Length; currentLatter++)
            {
                if (currentLatter < feedItemText.Length && char.IsLetter(feedItemText[currentLatter]))
                    continue;

                if (currentLatter > firstLatter && !tagOpened)
                {
                    var word = feedItemText.Substring(firstLatter, currentLatter - firstLatter).ToUpper();
                    if (words.ContainsKey(word))
                        words[word]++;
                    else
                        words.Add(word, 1);
                }
                firstLatter = currentLatter + 1;
                if (currentLatter < feedItemText.Length)
                {
                    tagOpened = tagOpened
                                    ? feedItemText[currentLatter] != '>'
                                    : feedItemText[currentLatter] == '<';
                }

            }
            return words;
        }
    }
}
